package org.wheel.plugins.starter.toolkit.spi.annotation.support;

import jakarta.annotation.PostConstruct;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.ConstructorBinding;
import org.springframework.lang.Nullable;
import org.wheel.plugins.toolkit.sql.spi.register.AnnotationRegistry;
import org.wheel.plugins.toolkit.sql.spi.annotation.support.DefaultAnnotationProvider;

import java.util.List;

/**
 * Spring-Boot 专用：读取 application.yml 里
 * wheel.sql.annotation.table / column / id 列表，
 * 把用户自定义的注解也批量注册。
 *
 * 使用步骤：
 *   1. 在当前模块 resources/META-INF/spring.factories 里加一行
 *        org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
 *        org.wheel.plugins.toolkit.spi.annotation.support.SpringBootAnnotationProvider
 *      （或者 spring-boot 2.7+ 用 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports）
 *   2. 用户 yml 示例：
 *        wheel:
 *          sql:
 *            annotation:
 *              table:
 *                - com.baomidou.mybatisplus.annotation.TableName
 *              column:
 *                - com.baomidou.mybatisplus.annotation.TableField
 *              id:
 *                - com.baomidou.mybatisplus.annotation.TableId
 */
@ConfigurationProperties(prefix = "wheel.sql.annotation")
public class SpringBootAnnotationProvider {

    private final List<String> table;
    private final List<String> column;
    private final List<String> id;

    @ConstructorBinding
    public SpringBootAnnotationProvider(@Nullable List<String> table,
                                        @Nullable List<String> column,
                                        @Nullable List<String> id) {
        this.table = table == null ? List.of() : table;
        this.column = column == null ? List.of() : column;
        this.id = id == null ? List.of() : id;
    }

    @PostConstruct
    public void register() {
        // 1. 先保证默认注解一定在内
        DefaultAnnotationProvider.registerDefaults();

        // 2. 再注册用户自定义
        table.forEach(c -> AnnotationRegistry.registerTableAnnotation(forName(c)));
        column.forEach(c -> AnnotationRegistry.registerColumnAnnotation(forName(c)));
        id.forEach(c -> AnnotationRegistry.registerIdAnnotation(forName(c)));
    }

    @SuppressWarnings("unchecked")
    private Class<? extends java.lang.annotation.Annotation> forName(String name) {
        try {
            return (Class<? extends java.lang.annotation.Annotation>) Class.forName(name);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("annotation class not found: " + name, e);
        }
    }
}